<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>车辆备案</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">场内车辆备案</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div class="inside-main-box">
          <el-row class="inside-main" >
            <el-col :span="5" style="margin-left: 20px">
              <el-form-item label="申请时间" size="small">
                <el-date-picker clearable v-model="form.startDateTime" type="date" placeholder="选择时间" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <span>-</span>
            <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="" size="small">
                <el-date-picker clearable v-model="form.endDateTime" type="date" placeholder="选择时间" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="管理号码" size="small">
                <el-input clearable v-model="form.environmentalProtectionGrade" maxLength="100" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col v-if="factoryId == 0" :span="4" style="margin-left: 5px">
              <el-form-item label="所属工厂" size="small">
                <el-select v-model="form.factory_id" placeholder="请选择工厂" clearable>
                  <el-option v-for="fa in factory.factorys" :label="fa.factory_name" :key="fa.id" :value="fa.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin:0  20px 10px">
              <el-button size="small" class="sele-but" icon="search" @click="selectQuery">查询</el-button>
              <el-button size="small" icon="refresh" class="empty-but" @click="onReset">重置</el-button>
            </el-col>
          </el-row>
          <div></div>
        </div>
        <div style="height: 45px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
          <el-button size="small" icon="plus" class="add-but" @click="addPage()" style=margin-left:20px>新增</el-button>
          <el-button type="danger" plain size="small" icon="delete" @click="deleteAll">删除</el-button>
          <el-button size="small" class="empty-but" icon="upload" @click="dialogTableVisible = true">导入</el-button>
          <el-button size="small" class="empty-but" icon="download" @click="exportExcelData(form)">导出</el-button>
        </div>
        <!-- 导入弹出框 -->
        <el-dialog style="width: 600px" v-model="dialogTableVisible" center title="导入文件">
  <el-upload :file-list="state.fileList" action='#' drag :http-request="uploadAction" :on-exceed="handleExceed"
    :limit="1" :show-file-list="false" :auto-upload="true" :before-upload="beforeUpload" style="width: 100%;" class="left-view">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件托到此处或<em>点击导入</em>
            </div>
            <template #tip>
              <div style="text-align:center;margin-top:10px">
               <p style="font-size:14px;">支持上传xsl格式文件,如果没有模板
               <a style="text-decoration:none;" href="template/场内车辆导入模板.xls" download>
               <el-button link  type="primary" size="mini">点击下载</el-button></a>>
              </p>
              </div>
            </template>
          </el-upload>
        </el-dialog>
        <div style="background: #fff">
          <el-table :data="tableData"  style="width: 100%;" height="460" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" align="center" width="50"/>
            <el-table-column align="center" prop="factory_id" label="工厂" width="90px" show-overflow-tooltip>
              <template #default="item">
                <span v-if="item.row.factory_id">{{factory.factoryNames[item.row.factory_id]?.factory_name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="environmentalProtectionGrade" width="180px" show-overflow-tooltip align="center" label="环保登记编码内部管理号牌"/>
            <!--
            <el-table-column align="center" prop="state" label="状态">
            <template #default="scope">
               <el-button link v-if="scope.row.state== 0" size="danger" type="primary">停用</el-button>
               <el-button link  v-if="scope.row.state== 1" size="success" type="primary">启用</el-button>
            </template>
          </el-table-column>
          -->
            <el-table-column prop="licensePlateColor" label="车牌颜色" align="center" show-overflow-tooltip/>
            <el-table-column align="center" prop="drivingLicense" label="行驶证正本">
              <template #default="scope">
                <el-button  v-if="scope.row.drivingLicense==null" type="primary" size="small"  link >未上传</el-button>
               <el-button v-else type="primary" size="small"  link @click="drivingLicenselist(scope.row)">查看照片</el-button>
              </template>
            </el-table-column>
           <el-table-column align="center" prop="vehiclePhoto" label="行驶证副本" >
             <template #default="scope">
                <el-button  type="primary" size="small" v-if="scope.row.vehiclePhoto==null" link >未上传</el-button>
                 <el-button  v-else  type="primary" size="small" link @click="vehiclelist(scope.row)">查看图片</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="accompanyingList" label="随车清单">
              <template #default="scope">
                <el-button  v-if="scope.row.accompanyingList==null" type="primary" size="small" link >未上传</el-button>
               <el-button v-else type="primary" size="small"  link @click="acclist(scope.row)">查看照片</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="vehicleType" label="车辆类型" align="center" show-overflow-tooltip/>
            <el-table-column prop="registrationDate" label="注册时间" align="center" width="100px" show-overflow-tooltip
              :formatter="function(row,column){ if(row.registrationDate){ return $moment(row.registrationDate).format('YYYY-MM-DD')  }else{  return '' }}" />
             <el-table-column prop="applicationTime" label="申请时间" align="center" width="180px" show-overflow-tooltip
              :formatter="function(row,column){ if(row.applicationTime){ return $moment(row.applicationTime).format('YYYY-MM-DD HH:mm:ss')  }else{  return '' }}" />
            <el-table-column prop="vehicleEmissions" label="排放阶段" align="center" show-overflow-tooltip/>
            <el-table-column label="操作" align="center" fixed="right" width="200px">
              <template #default="scope">
                <!--
                <el-button link v-if="scope.row.state== 1" size="danger" icon="close" @click="forbiddenRow(scope.row.onSsiteVehicleFilingForm_id)" type="primary">停用</el-button>
                <el-button link  v-if="scope.row.state== 0" size="success" icon="check" @click="openRow(scope.row.onSsiteVehicleFilingForm_id)" type="primary">启用</el-button>
                -->
                <el-button link type="primary" size="small" icon="view" @click="detailPage(scope.row)">详情</el-button>
                <el-button link type="primary" size="small" icon="edit" @click="update(scope.row)">修改</el-button>
                <!--<el-button link type="danger" size="small" icon="delete" @click="delect(scope.row)">删除</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
           size="small"   layout="prev, pager, next, jumper,total"
           :total="queryInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </el-main>
          <!--照片弹窗-->
      <el-dialog v-model="vehiclePhotoDia"  center>
        <div  class="photoDiv">
          <img class="photoImg" :src='Image.vehiclePhoto' alt=""/></div>
      </el-dialog>
      <el-dialog v-model="accompanyingListDia"  center>
        <div class="photoDiv">
          <img class="photoImg" :src='Image.accompanyingList' alt=""/></div>
      </el-dialog>
      <el-dialog v-model="drivingLicenseDia"  center>
        <div class="photoDiv">
          <img class="photoImg" :src='Image.drivingLicense' alt=""/></div>
      </el-dialog>
    </el-container>
  </div>
</template>
<script>
import { reactive, ref, onMounted } from "vue";
import { Plus, UploadFilled } from "@element-plus/icons-vue";

//接口导入
import {
  uploadOnsite,
  deleteOnsite,
  selectOnsiteAll,
  selectOnsiteQuery, updateOnsiteState,
  deleteAllOnSite
} from "@/api/mobilePollution";
// 路由
import { useRouter } from "vue-router";
import {getFactoryInfo} from "../../../api/factory";
// 文件导入
import moment from "moment";
import { ElMessage, ElMessageBox ,UploadRawFile,uploadFile, FormInstance, Action} from "element-plus";
import * as XLSX from "xlsx";
import {onsiteListOut} from "@/api/leadingOut";
import { v3ImgPreviewFn } from 'v3-img-preview'
export default {
  setup() {
    // 路由
    const router = useRouter();
    //    定义
    const tableData = ref([]);
    const formRef = ref(null);
    let factory=reactive({factorys:[],factoryNames:{}});
    const getFactorys = ()=>{
      getFactoryInfo({pageSize:1000}).then(res=>{
        let factorys = [];
        res.data?.list.forEach(e=>{
          factorys.push(e);
          factory.factoryNames[e.id]=e;
        })
        factory.factorys = factorys;
      })
    }
    const form = reactive({
      startDateTime: "",
      endDateTime: "",
      environmentalProtectionGrade: "",
    });
    let factoryId = localStorage.getItem('factoryId')
    const multipleSelection = ref([])
    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }
    const deleteAll = () => {
      if(multipleSelection.value.length == 0){
        ElMessage.error("请选择要删除的数据")
      }else{
        ElMessageBox.confirm("确定要删除吗?").then(()=>{
          deleteAllOnSite(multipleSelection.value).then((res)=>{
            if(res.code == 200){
              ElMessage.success("删除成功")
              selectQuery()
            }else {
              ElMessage.error('删除失败')
            }
          })
        })
      }
    }
    // 重置
    const onReset = () => {
      form.startDateTime = "";
      form.endDateTime = "";
      form.environmentalProtectionGrade = "";
      queryInfo.pagesize='10',
      queryInfo.pagenum = '1'
      selectQuery()
    };
    // 新增跳转到新增页面
    const addPage = () => {
      router.push({
        path: "/onsiteAdd",
      });
    };
    // 跳转到详情页面
    const detailPage = (row) => {
      localStorage.setItem("userObj", JSON.stringify(row));
      router.push({
        path: "/onsiteDetail",
        query: "",
      });
    };
    // 跳转到修改页面
    const update = (row) => {
      localStorage.setItem("userObj", JSON.stringify(row));
      router.push({
        path: "/onsiteUpdate",
        query: "",
      });
    };
    //分页
    const queryInfo = reactive({
      pagenum:1,
      pagesize:10,
      total:0
    })
    const handleSizeChange = (val) => {
      queryInfo.pagesize = val
      selectQuery()
    }
    //点击第几页
    const handleCurrentChange = (val) => {
      queryInfo.pagenum = val
      selectQuery()
    }
    //查询全部接口
    // const select = () => {
    //   selectOnsiteQuery({pageNum:queryInfo.pagenum,pageSize:queryInfo.pagesize}).then((res) => {
    //     tableData.value = res.data.list;
    //     queryInfo.total=res.data.total;
    //   });
    // };
    onMounted(() => {
      localStorage.removeItem("userObj");
      selectQuery();
      getFactorys()
    });
    //搜索查询
    const selectQuery = () => {
      if(form.startDateTime){
        let startDate = moment(form.startDateTime).format('YYYY-MM-DD')
        form.startDateTime = startDate
      }
      if(form.endDateTime){
        let endDate = moment(form.endDateTime).format('YYYY-MM-DD')
        form.endDateTime = endDate
      }
      form.pageSize = queryInfo.pagesize
      form.pageNum = queryInfo.pagenum
      selectOnsiteQuery(form).then((res) => {
        if (res.code == 200) {
          tableData.value = res.data.list
          queryInfo.total=res.data.total;
        } else {
        }
      });

    };
    //删除
    const delect = (row) => {
      ElMessageBox.confirm("确定要删除吗?").then(()=>{
        deleteOnsite(row).then((res)=>{
          selectQuery()
        })
      })
    };
    //修改禁行状态 --禁用
    const forbiddenRow= (index) => {
      ElMessageBox.confirm("确定要停用吗?").then(()=>{
        updateOnsiteState({onSsiteVehicleFilingForm_id:index,state:"0"}).then((res)=>{
          selectQuery()
        })
      })
    }
//修改禁行状态 --启用
    const openRow= (index) => {
      ElMessageBox.confirm("确定要启用吗?").then(()=>{
        updateOnsiteState({onSsiteVehicleFilingForm_id:index,state:"1"}).then((res)=>{
          selectQuery()
        })
      })
    }
    // 导入
    const dialogTableVisible = ref(false);
    const uploadFile = ref();
    const state = reactive({
      bannerUrl: '',
      fileList: [],
      fileName: '',
    })

    const clearFiles = () => {
      ref.uploadFile.clearFiles();
    }
    const beforeUpload = (file) => {
    //   console.log(file,'file')
    //   // const type = ['image/jpeg', 'image/jpg', 'image/png']
    //   const type = ['application/vnd.ms-excel']
    //   if (type.indexOf(file.type) === -1) {
    //     // ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
    //     ElMessage.error('上传的文件必须是xls,xlsx')
    //     return false
    //   } else if (file.size / 1024 / 1024 > 2) {
    //     ElMessage.error('文件大小不能超过2MB!')
    //     return false
    //   }
    }
    const handleExceed = (files, fileList) => {
      if (state.fileList.length >= 1) {
        ElMessage.error('只能上传一个文件')
        return;
      }
    }
    const uploadAction = (option) => {
      let param = new FormData();
      param.append('multipartFile', option.file);
      uploadOnsite(param).then((res) => {
        if (res.code === 200) {
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.success(res.data);
          selectQuery()
        }else if(res.code == 701){
          state.fileList = []
          dialogTableVisible.value = false
          messageLog.value = res.msg
          ElMessage.error(res.data)
        }else if(res.code == 605){
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.error(res.data)
        }else{
          state.fileList = []
          dialogTableVisible.value = false
          ElMessage.error('文件导入失败')
        }
      }).catch(error => {
        state.fileList = []
        dialogTableVisible.value = false
        ElMessage.error('文件导入失败')
      });
    }
    const Image = reactive({
      vehiclePhoto:"",
      accompanyingList:"",
      drivingLicense:"",
    })
    //行驶证副本显示图片
    const vehiclePhotoDia = ref(false);
    const vehiclelist = (row) => {
      // vehiclePhotoDia.value = true;
      Image.vehiclePhoto = `${process.env.VUE_APP_BASE_API}\/${row.vehiclePhoto}`
      v3ImgPreviewFn(Image.vehiclePhoto)
    };
    //随车清单显示图片
    const accompanyingListDia = ref(false);
    const acclist = (row) => {
      // accompanyingListDia.value = true;
      Image.accompanyingList = `${process.env.VUE_APP_BASE_API}\/${row.accompanyingList}`
      v3ImgPreviewFn(Image.accompanyingList)
    };
    //行驶证正本显示图片
    const drivingLicenseDia = ref(false);
    const drivingLicenselist = (row) => {
      // drivingLicenseDia.value = true;
      Image.drivingLicense = `${process.env.VUE_APP_BASE_API}\/${row.drivingLicense}`
      v3ImgPreviewFn(Image.drivingLicense)
    };
    const handlePreview = (file) => {

    }; // 导入弹出框
    let table = reactive({
      rows: [],
      total: 0,
    });
    //  导出英文(数据库字段)
    // const exportExcel = () => {
    //   const data = XLSX.utils.json_to_sheet(tableData.value); //此处tableData.value为表格的数据
    //   const wb = XLSX.utils.book_new();
    //   XLSX.utils.book_append_sheet(wb, data, "test-data"); //test-data为自定义的sheet表名
    //   XLSX.writeFile(wb, "场内车辆.xlsx"); //test.xlsx为自定义的文件名
    // };
    //导出工序(中文)
    const exportExcelData = (form) => {
      ElMessageBox.confirm("确定要导出吗?").then(() => {
        onsiteListOut(form).then((res)=>{
          if (res.data.length == 0){
            ElMessage.error("未查询到数据")
          }else {
            out.value = res.data
            exportExcel()
          }
         })
      })
    }
    const out = ref()
    const exportExcel = () => {

      let exportData = []
      //导出数据结构构造
      out.value.forEach(item => {
        if(item.obdInstallationDate){
          item.obdInstallationDate = moment(item.obdInstallationDate).format('YYYY-MM-DD')
        }else {
          item.obdInstallationDate = ''
        }
        if(item.registrationDate){
          item.registrationDate = moment(item.registrationDate).format('YYYY-MM-DD')
        }else {
          item.registrationDate = ''
        }
        item.factory_id = factory.factoryNames[item.factory_id]?.factory_name
        exportData.push({
          factory_id:item.factory_id ? item.factory_id : '',
          environmentalProtectionGrade: item.environmentalProtectionGrade ? item.environmentalProtectionGrade : '',
          enterpriseName: item.enterpriseName ? item.enterpriseName : '',
          obdInstallationDate: item.obdInstallationDate ? item.obdInstallationDate : '',
          natureOfVehicleUse: item.natureOfVehicleUse ? item.natureOfVehicleUse : '',
          owner: item.owner ? item.owner : '',
          address: item.address ? item.address : '',
          obdInstallation: item.obdInstallation ? item.obdInstallation : '',
          licensePlateColor: item.licensePlateColor ? item.licensePlateColor : '',
          vehicleType: item.vehicleType ? item.vehicleType : '',
          brandModel: item.brandModel ? item.brandModel : '',
          engineNumber: item.engineNumber ? item.engineNumber : '',
          registrationDate: item.registrationDate ? item.registrationDate : '',
          vehicleIdentificationNumber: item.vehicleIdentificationNumber ? item.vehicleIdentificationNumber : '',
          vehicleEmissions: item.vehicleEmissions ? item.vehicleEmissions : '',
          vehicleFuel: item.vehicleFuel ? item.vehicleFuel : '',
          // accompanyingList: item.accompanyingList ? item.accompanyingList : '',
          // drivingLicense: item.drivingLicense ? item.drivingLicense : '',
          // vehiclePhoto: item.vehiclePhoto ? item.vehiclePhoto : ''
        })
      })
      //导出表头设计
      let head = {
        factory_id:'工厂',
        // cl_cph: '车牌号',
        environmentalProtectionGrade: '环保等级编码内部管理号牌',
        enterpriseName:'企业名称',
        obdInstallationDate:'OBD安装日期',
        natureOfVehicleUse:'使用性质',
        owner:'所有人',
        address:'住址',
        obdInstallation:'是否安装OBD',
        licensePlateColor:'车牌颜色',
        vehicleType:'车辆类型',
        brandModel:'品牌型号',
        engineNumber:'发动机号码',
        registrationDate:'注册日期',
        vehicleIdentificationNumber:'车辆识别代码(VIN)',
        vehicleEmissions:'排放阶段',
        vehicleFuel:'燃料类型',
        // accompanyingList:'随车清单',
        // drivingLicense:'行驶证正本',
        // vehiclePhoto:'行驶证副本'
      }
      //表头数据切换
      const list = exportData.map(item => {
        const obj = {}
        for (const k in item) {
          if (head[k]) {
            obj[head[k]] = item[k]
          }
        }
        return obj
      })
      // 创建工作表
      const data = XLSX.utils.json_to_sheet(list)
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      // 将工作表放入工作簿中
      XLSX.utils.book_append_sheet(wb, data, 'data')
      // 生成文件并下载
      XLSX.writeFile(wb, '场内车辆.xlsx')

    }
    return {
      factoryId,
      getFactorys,
      factory,
      exportExcelData,
      forbiddenRow,
      openRow,
      queryInfo,
      handleCurrentChange,
      handleSizeChange,
      tableData,
      onReset,
      form,
      // select,
      selectQuery,
      addPage,
      delect,
      update,
      detailPage,
      exportExcel,
      dialogTableVisible,
      state,
      uploadAction,
      beforeUpload,
      handleExceed,
      vehiclelist,
      vehiclePhotoDia,
      Image,
      acclist,
      accompanyingListDia,
      drivingLicenselist,
      drivingLicenseDia,
      multipleSelection,
      handleSelectionChange,
      deleteAll
    };
  },
};
</script>
<style scoped>
/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}

.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/*照片弹窗及图片样式*/
.photoImg{
  vertical-align:middle;width:100%;height:600px;margin:auto
}
.photoDiv{
  width:100%;display:flex
}
/* 分页 */

.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
